package com.example.utils;

import io.jsonwebtoken.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class JwtUtils {
    private String secret="yyds";
    private Long expiration=1000*60*60*24l;

    private String generateToken(Map<String,Object> claims){
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS256,secret).compact();

    }

    public String generateToken(Integer userid,String username,Integer userType){
        Map<String,Object> claims= new HashMap<>(4);
        //设置token分类
        claims.put("userId",userid);
        claims.put("username",username);
        claims.put("userType",userType);
        //设置签发时间为当前时间
        claims.put(Claims.ISSUED_AT,new Date());
        return generateToken(claims);
    }

    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {
            claims=Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims=null;
        }
        return claims;

    }

    public Integer getUserIdFromToken(String token){
        Integer userId;
        try{
            Claims claims =getClaimsFromToken(token);
            userId=(Integer) claims.get("userId");
        }catch (Exception e){
            userId=null;
        }
        return userId;
    }
    public String getUsernameFromToken(String token){
        String username;
        try{
            Claims claims =getClaimsFromToken(token);
            username=(String) claims.get("username");
        }catch (Exception e){
            username=null;
        }
        return username;
    }
    public Integer getUserTypeFromToken(String token){
        Integer UserType;
        try{
            Claims claims =getClaimsFromToken(token);
            UserType=(Integer) claims.get("userType");
        }catch (Exception e){
            UserType=null;
        }
        return UserType;
    }
    public String refreshToken(String token){
        String refreshedToken;
        try{
            Claims claims =getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT,new Date());
            refreshedToken=generateToken(claims);
        }catch (Exception e){
            refreshedToken=null;
        }
        return refreshedToken;
    }

}
